<template>
  <div class="clearfix">
    <a-upload
      :beforeUpload="beforeImageUpload"
      list-type="picture-card"
      :file-list="imageList"
      :multiple="multiple"
      :disabled="disabled"
      @change="handleImageChange"
      @preview="handlePreview"
      :customRequest="customRequest"
    >
      <div v-if="imageList.length < limitNum && !disabled">
        <a-icon type="plus" />
        <div class="ant-upload-text">上传</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script>
import { COMMON_UPLOADPIC } from '../../api/global.js'
import { commonPromise } from '@/http'
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}

export default {
  props: {
    defaultImageList: {
      type: Array,
      default: function () {
        return []
      },
      required: true
    },
    fileTypeList: {
      type: Array,
      default: function () {
        return []
      },
      required: false
    },
    limitSize: {
      type: Number,
      default: 5,
      required: false
    },
    limitNum: {
      type: Number,
      default: 20,
      required: false
    },
    multiple: {
      type: Boolean,
      default: false,
      required: false
    },
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    latitude: {
      // 纬度
      type: String,
      default: '10'
    },
    longitude: {
      // 经度
      type: String,
      default: '100'
    },
    type: {
      // 附件类型(1:图片;2:其他;3:视频)
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      previewVisible: false,
      previewImage: '',
      imageList: []
    }
  },
  watch: {
    defaultImageList(newVal) {
      this.imageList = this.handleData(newVal)
    }
  },
  created () {
    this.imageList = this.handleData(this.defaultImageList)
  },
  methods: {
    // ---------------------------------------------img--start
    beforeImageUpload (file) {
      return new Promise((resolve, reject) => {
        if (this.fileTypeList.length > 0) {
          const index = this.fileTypeList.indexOf(file.type)
          if (index > 0) {
            this.$message.error(`您只能上传${this.fileTypeList[index]}文件`)
          }
        }
        const limitSize = file.size / 1024 / 1024 < this.limitSize
        if (!limitSize) {
          this.$message.error(`文件大小不能大于${this.limitSize}MB`)
          return reject(new Error(`文件大小不能大于${this.limitSize}MB`))
        }
        return resolve(true)
      })
    },
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      console.log(file)
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleCancel () {
      this.previewVisible = false
    },
    customRequest (data) {
      console.log(data)
      const file = data.file
      let formdata = new FormData()
      formdata.append('img', file)
      // console.log(this.$api.commonUploadPicFetch)
      // eslint-disable-next-line no-new
      new Promise((resolve) => {
        // let url = `${COMMON_UPLOADPIC}?latitude=${this.latitude}&longitude=${this.longitude}&type=${this.type}`
        let url = COMMON_UPLOADPIC
        let params = {
          latitude: this.latitude,
          longitude: this.longitude,
          type: this.type
        }
        // const diyUploadPicFetch = function (data) { commonPromise() }
        commonPromise({ data: formdata, params, url, method: 'post' })
          .then((res) => {
            console.log(res)
            let index = this.genId(5)
            let antObj = {
              uid: index,
              name: index,
              status: 'done'
            }
            const imaObj = Object.assign(antObj, res.data)
            this.imageList = [
              ...this.imageList.filter((item) => item.status === 'done'),
              imaObj
            ]
            console.log(this.imageList)
            this.handleChange()
            this.$message.success(`上传图片【${file.name}】成功`)
            // this.$router.back()
            this.handleChange()
            resolve(res.data)
          })
          .catch((err) => {
            console.log(err)
            this.$message.error(`上传图片【${file.name}】出错`)
          })
        /*
        this.$api.commonUploadPicFetch(formdata).then((res) => {
          console.log(res)
          let index = this.genId(5)
          let antObj = {
            uid: index,
            name: index,
            status: 'done'
          }
          const imaObj = Object.assign(antObj, res.data)
          this.imageList = [
            ...this.imageList.filter((item) => item.status === 'done'),
            imaObj
          ]
          console.log(this.imageList)
          this.handleChange()
          this.$message.success(`上传图片【${file.name}】成功`)
          // this.$router.back()
          this.handleChange()
          resolve(res.data)
        }).catch((err) => {
          console.log(err)
          this.$message.error(`上传图片【${file.name}】出错`)
        })
        */
      })
    },
    handleImageChange (info) {
      let fileList = [...info.fileList]
      this.imageList = fileList
      this.handleChange()
    },
    handleChange () {
      let index = this.imageList
        .filter((item) => item.url)
        .map((item) => {
          return item
        })
      console.log(this.imageList)
      this.$emit('change', index ? index : [])
    },
    genId (length) {
      return Number(
        Math.random().toString().substr(3, length) + Date.now()
      ).toString(36)
    },
    handleData (list) {
      console.log(list)
      return list.map((item) => {
        let index = this.genId(5)
        let antObj = {
          uid: index,
          name: index,
          status: 'done'
        }
        console.log(Object.assign(antObj, item))
        return Object.assign(antObj, item)
      })
    }
    // ---------------------------------------------img--end
  }
}
</script>
<style>
.ant-upload-list-picture-card .ant-upload-list-item,
.ant-upload.ant-upload-select-picture-card,
.ant-upload-list-picture-card-container {
  width: 200px;
  height: 200px;
}

/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
